<?php
declare (strict_types = 1);

namespace app\controller;

use app\BaseController;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Request;
use app\model\ProductUnits as ProductUnitsModel;
use think\Response;
use think\response\Json;

class ProductUnits extends BaseController
{
    protected ProductUnitsModel $model;
    public function initialize(): void
    {
        $this->model = new ProductUnitsModel();
    }

    /**
     * 显示资源列表
     * @return Json
     */
    public function index(): Json
    {
        try {
            $result = $this->model->getAllUnits();
            return apiResponse(200, '获取所有单位成功', $result);
        } catch (DataNotFoundException|DbException $e) {
            return apiResponse($e->getCode(), $e->getMessage());
        }
    }

    /**
     * 保存新建的资源
     * @param Request $request
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function save(Request $request): Json
    {
        $payload = $request->post('name');
        $stringArr = explode(',', string:$payload);
        $data = [];
        if(count($stringArr)>0){
            foreach ($stringArr as $item){
                $data[] = ['name'=>$item];
            }
        }
        $result = $this->model->createUnit($payload,$data);
        return apiResponse($result['code'], $result['message']);
    }

    /**
     * 保存更新的资源
     * @param Request $request
     * @param $id
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function update(Request $request, $id): Json
    {
        $data = $request->put();
        $result = $this->model->updateUnit($id,$data);
        return apiResponse($result['code'], $result['message']);
    }

    /**
     * 删除指定资源
     * @param $id
     * @return Json
     */
    public function delete(int $id): Json
    {
        $result = $this->model->deleteUnit($id);
        return apiResponse($result['code'], $result['message']);
    }
}
